package com.smzd.projforge.business;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smzd.core.business.AbstractService;
import com.smzd.core.dao.IDao;
import com.smzd.core.utils.db.RPage;
import com.smzd.core.utils.db.SRPage;
import com.smzd.core.utils.json.FGRowConverter;
import com.smzd.projforge.dao.DynaAttributeDao;
import com.smzd.projforge.domain.DynaAttribute;
import com.smzd.projforge.domain.DynaClass;

@Service
public class DynaAttributeService extends AbstractService<DynaAttribute> {
	@Autowired
	private DynaAttributeDao dao;
	@Override
	protected IDao<DynaAttribute> getDao() {
		return dao;
	}

	@Override
	protected FGRowConverter<DynaAttribute> getConverter() {
		return ConverterHolder.converter;
	}

	static class ConverterHolder{
		static final FGRowConverter<DynaAttribute> converter = new FGRowConverter<DynaAttribute>() {
			@Override
			public Object[] convert(DynaAttribute elem) {
				String propClass = null;
				Integer refClassId = null;
				Integer projectId = null;
				Object[] list = null;
				DynaClass clazz = elem.getRefClass();
				if(clazz!=null){
					propClass = clazz.getName();
					refClassId = clazz.getId();
					projectId = elem.getScope().getScope().getId();
					list = new Object[]{propClass,
							refClassId,
							projectId};
				}
				Object[] fs = new Object[]{
						elem.getId(),
						elem.getName(),
						elem.getAttributeName(),
						elem.getDescription(),
						elem.getType(),
						elem.getSize(),
						elem.getFormat(),
						elem.isNullable(),
						elem.isEternal(),
						elem.isSubList(),
						elem.isCarrier(),
						list
				};
				return fs;
			}
		};
		static final FGRowConverter<DynaAttribute> mtmConverter = new FGRowConverter<DynaAttribute>() {
			@Override
			public Object[] convert(DynaAttribute elem) {
				Object[] fs = new Object[]{
						elem.getId(),
						elem.getName(),
						AbstractService.getObjectByField(elem.getRefClass())
				};
				return fs;
			}
			
		};
	}

	@Override
	public String getListDataJson(RPage<DynaAttribute> paging) {
		@SuppressWarnings("unchecked")
		SRPage<DynaClass, DynaAttribute> page = (SRPage<DynaClass, DynaAttribute>) paging;
		getDao().getElemsByPage(page);
		List<DynaAttribute> attributes = page.getElems();
		if(attributes!=null&&attributes.size()>0){
			for(DynaAttribute attribute : attributes){
				attribute.setScope(page.getScope());
			}
		}
		return page.toFlexiGridJsonString(getConverter());
	}

	public String getMTMAttributeCandidates(int scopeId) {
		SRPage<DynaClass, DynaAttribute> page = new SRPage<>();
		page.setScope(new DynaClass(scopeId));
		page.setPageNo(1);
		page.setPageSize(999);
		dao.getMTMAttributeCandidates(page);
		return page.toFlexiGridJsonString(ConverterHolder.mtmConverter);
	}
}
